import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.manifold import Isomap, LocallyLinearEmbedding, TSNE, SpectralEmbedding
from sklearn.preprocessing import StandardScaler
from time import time

# 加载本地MNIST数据集
print("Loading MNIST dataset from local CSV...")

# 读取训练数据
train_df = pd.read_csv('train.csv')
# 假设最后一列是标签，其余列是784像素数据
X = train_df.iloc[:, :-1].values.astype(np.float32)
y = train_df.iloc[:, -1].values.astype(np.uint8)

# 标准化数据
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 显示原始图像
print("Displaying original images...")
plt.figure(figsize=(10, 5))
for i in range(10):
    plt.subplot(2, 5, i+1)
    plt.imshow(X[i].reshape(28, 28), cmap='gray')
    plt.title(f"Label: {y[i]}")
    plt.axis('off')
plt.tight_layout()
plt.show()

# 定义降维方法
methods = [
    ("PCA", PCA(n_components=2)),
    ("Isomap", Isomap(n_components=2, n_neighbors=10)),
    ("LLE", LocallyLinearEmbedding(n_components=2, n_neighbors=10, method='standard')),
    ("Laplacian Eigenmaps", SpectralEmbedding(n_components=2, n_neighbors=10)),
    ("t-SNE", TSNE(n_components=2, perplexity=30, n_iter=1000))
]

# 应用每种降维方法并可视化
plt.figure(figsize=(15, 12))
for i, (name, method) in enumerate(methods, 1):
    print(f"Running {name}...")
    start_time = time()
    
    # 应用降维
    X_embedded = method.fit_transform(X_scaled)
    
    # 计算运行时间
    duration = time() - start_time
    print(f"{name} took {duration:.2f} seconds")
    
    # 绘制结果
    plt.subplot(2, 3, i)
    scatter = plt.scatter(X_embedded[:, 0], X_embedded[:, 1], c=y, cmap='tab10', alpha=0.6)
    plt.title(f"{name} (time: {duration:.2f}s)")
    plt.colorbar(scatter, label='Digit')
    
plt.tight_layout()
plt.show()